package com.youthburin.rmp.services.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youthburin.base.services.AbstractService;
import com.youthburin.base.springjpa.MyRepository;
import com.youthburin.rmp.domain.RmpUser;
import com.youthburin.rmp.repositories.RmpUserRepository;
import com.youthburin.rmp.services.RmpUserService;
import com.youthburin.rmp.util.PasswordUtils;

@Service
public class RmpUserServiceImpl extends AbstractService<RmpUser, String> implements RmpUserService {
	@Autowired
	private RmpUserRepository rmpUserRepository;

	@Override
	public MyRepository<RmpUser, String> getMyRepository() {
		return rmpUserRepository;
	}

	@Override
	public RmpUser get(String code) {
		RmpUser user = super.get(code);

		return user;
	}

	@Override
	public RmpUser save(RmpUser rmpUser) {
		// 密码设置为默认密码
		rmpUser.setPassword(PasswordUtils.getEncodeInitailPassword(rmpUser.getCode()));

		RmpUser newRmpUser = rmpUserRepository.save(rmpUser);
		return newRmpUser;
	}

	@Override
	public RmpUser update(RmpUser rmpUser) {
		// 更新时不能将用户密码更新掉
		if (StringUtils.isNotBlank(rmpUser.getCode())) {
			RmpUser oldRmpUser = get(rmpUser.getCode());
			if (oldRmpUser != null) {
				rmpUser.setPassword(oldRmpUser.getPassword());

				super.update(rmpUser);

				return rmpUser;
			}
		}
		return null;
	}
}
